﻿namespace SS.WPF.Framework.Restriction
{
    using System;
    using System.Linq;
    using System.Xml.Serialization;

    public abstract class EnumRestriction<T> : BaseRestriction<T>, IEnumRestriction
    {
        public Type EnumType { get; set; }

        public override string Description
        {
            get
            {
                return string.Format("[{0}]",
                                     string.Join(", ", Enum.GetValues(EnumType).Cast<object>().Select(x => x.ToString())));
            }
        }

        public override bool CanParse(string text)
        {
            try
            {
                Convert.ChangeType(text, typeof (T));
            }
            catch
            {
                return false;
            }

            return true;
        }

        public static string ConvertToString(Enum e)
        {
            // Get the Type of the enum
            var t = e.GetType();

            // Get the FieldInfo for the member field with the enums name
            var info = t.GetField(e.ToString("G"));
            // Check to see if the XmlEnumAttribute is defined on this field
            if (!info.IsDefined(typeof (XmlEnumAttribute), false))
            {
                // If no XmlEnumAttribute then return the string version of the enum.
                return e.ToString("G");
            }
            else
            {
                // Get the XmlEnumAttribute
                var o = info.GetCustomAttributes(typeof (XmlEnumAttribute), false);
                var att = (XmlEnumAttribute) o[0];
                return att.Name;
            }
        }
    }
}